RSpec与设计

我刚接触到rails :)我试图运行我的第一个测试。 为什么这个测试通过? 用户名应该至少有2个字符,我的用户名有更多,它仍然通过测试。

user.rb:

validates :username, :length => { :minimum => 2 } 

user_spec.rb

 require 'spec_helper' describe User do before do @user = User.new(username: "Example User", email: "user@example.com", password: "foobar", password_confirmation: "foobar") end describe "when name is not present" do before { @user.username="aaaahfghg" } it { should_not be_valid } end end 

 describe "when name is not present" do before { @user.username = "aaaahfghg" } it { should_not be_valid } end 

首先,你的describe块正在测试错误的东西。 如果您想测试“名称不存在”,您应该设置:

@ user.username =“”#使用户名为空。

但是,为了检查用户名是否为空,您应该添加validates :username, presence: true 。 虽然您可能不需要它,因为您有{ minimum: 2 }validation

现在, @user.username = "aaaahf" #更好的写作方式是’a’* 5例如,它创建一个5 a = aaaaa的字符串。

这表示您的用户名超过2个字符,因此您的validation正常, { minimum: 2 }测试应该通过。

如果要确保用户名超过2个字符

 @user.username = 'a' 

希望有所帮助。

这一行:

 it { should_not be_valid } 

使用隐含主题 。 RSpec会自动创建一个User类的实例,然后您可以在it隐式使用it 。 但是您的测试然后创建另一个实例并将其分配给@user – 两个实例不相同。

如果要使用隐式主题,可以执行以下操作:

 subject { User.new(args) } before { subject.username = "aaaahfghg" } it { should_not be_valid }