我正在RSpec中编写模型测试,这是我的代码:
require "spec_helper"
describe User do
before do
@user = User.new(name: "Ryan", email: "email@email.com", password: "ryan", password_confirmation: "ryan")
end
subject { @user }
describe "Basic model properties" do
it { should respond_to(:name) }
it { should respond_to(:email) }
it { should respond_to(:password_digest) }
it { should respond_to(:password) }
it { should respond_to(:password_confirmation) }
it { should respond_to(:authenticate) }
#it { should be_valid }
end
describe "when name is not present" do
before { @user.name = "" }
it { should_not be_valid }
end
然而,当我使用bundle exec rspec spec/
运行它时,我收到一条错误,说“未定义的方法[]为nil:NilClass在它所说的行it { should_not be valid }
。如果我注释掉那行,那么测试通行证。
为什么我会遇到这个问题?
答案 0 :(得分:1)
尝试更改
describe "when name is not present" do
before { @user.name = "" }
it { should_not be_valid }
end
要
describe "when name is not present" do
before { subject.name = "" }
it { should_not be_valid }
end
有关详细信息,请参阅rspec docs https://www.relishapp.com/rspec/rspec-core/v/2-6/docs/subject/explicit-subject#access-subject-from-before-block
另外你可能想看看shoulda-matchers(https://github.com/thoughtbot/shoulda-matchers),然后你就不需要在前一块做任何特别的事情了
describe "Basic model properties" do
it { should respond_to(:name) }
it { should respond_to(:email) }
it { should respond_to(:password_digest) }
it { should respond_to(:password) }
it { should respond_to(:password_confirmation) }
it { should respond_to(:authenticate) }
it { should validate_presence_of(:name) }
end