Ruby on rails 为什么rspec中的实例变量为nil?
我有以下代码:Ruby on rails 为什么rspec中的实例变量为nil?,ruby-on-rails,ruby,rspec,Ruby On Rails,Ruby,Rspec,我有以下代码: before(:all) { @user = FactoryGirl.create(:user)} byebug subject { @user } it { should respond_to(:email)} it { should respond_to(:password)} it { should respond_to(:password_confirmation)} it { should be_valid } it { shoul
before(:all) { @user = FactoryGirl.create(:user)}
byebug
subject { @user }
it { should respond_to(:email)}
it { should respond_to(:password)}
it { should respond_to(:password_confirmation)}
it { should be_valid }
it { should validate_presence_of(:email) }
it { should validate_confirmation_of(:password) }
it { should allow_value('example@domain.com').for(:email)}
describe 'validations' do
subject { FactoryGirl.create(:user)}
it { should validate_uniqueness_of(:email).case_insensitive}
end
当它在byebug之后停止时,它发现@user为nil:
1: require 'rails_helper'
2:
3: describe User do
4: before(:all) { @user = FactoryGirl.create(:user)}
5: byebug
=> 6: subject { @user }
7: it { should respond_to(:email)}
8: it { should respond_to(:password)}
9: it { should respond_to(:password_confirmation)}
10:
(byebug) display @user
1: @user = nil
(byebug)
为什么会这样?如果我将FactoryGirl更改为User.create,则不会更改任何内容。将行从
before(:all) { @user = FactoryGirl.create(:user)}
到
允许(:user){FactoryGirl.create(:user)}
删除主题。现在,您将在用户变量中接收用户对象。
这是最佳做法。将行从
before(:all) { @user = FactoryGirl.create(:user)}
到
允许(:user){FactoryGirl.create(:user)}
删除主题。现在,您将在用户变量中接收用户对象。
这是最佳实践。在您的示例中
before(:all) { @user = FactoryGirl.create(:user)}
byebug
subject { @user }
@user
为nil
,因为byebug中断的是测试定义的级别,而不是测试的实际运行
将其更改为:
before(:all) {
@user = FactoryGirl.create(:user)
byebug
}
subject { @user }
顺便说一句:您可以编写以下内容以避免数据库访问并加快规格:
subject { FactoryGirl.build(:user) }
在你的例子中
before(:all) { @user = FactoryGirl.create(:user)}
byebug
subject { @user }
@user
为nil
,因为byebug中断的是测试定义的级别,而不是测试的实际运行
将其更改为:
before(:all) {
@user = FactoryGirl.create(:user)
byebug
}
subject { @user }
顺便说一句:您可以编写以下内容以避免数据库访问并加快规格:
subject { FactoryGirl.build(:user) }