2013-01-19 16 views
1

我有一个简单的用户工厂,看起来像这样:如何使用rspec和工厂女孩设置我的认证数据?

FactoryGirl.define do 
    factory :user do 
    name "jeff" 
    email "[email protected]" 
    password "foobar" 
    password_confirmation "foobar" 
    end 
end 

,我试图测试内置authenticate方法,像这样:

describe "return value of authenticate method", focus: true do 

    before do 
     create(:user) 
    end 

    let(:found_user) { User.find_by_email(:email) } 

    it "can return value of authenticate method" do 
     expect(:user).to eq found_user.authenticate(:password) 
    end 

    end 

我得到的错误是

NoMethodError: 
     undefined method `authenticate' for nil:NilClass 

这可能意味着found_user返回零。但我不明白为什么。当我在控制台上试用此代码时,它工作得很好。那么我做错了什么?我对Factory Girl很新颖。

我也在寻找的是没有使用实例变量的权利。

回答

1

试试这个

describe "return value of authenticate method", focus: true do 

    before do 
    @user = FactoryGirl.create(:user) 
    end 

    let(:found_user) { User.find_by_email(@user.email) } 

    it "can return value of authenticate method" do 
    expect(@user).to eq found_user.authenticate(@user.password) 
    end 
end 
+0

这个工程,但我想知道为什么只使用(:用户)不起作用。 –

+1

因为您已将:user factory的值分配给@user。这就像一堂课。你必须先实例化它。 –

+0

那么用户工厂返回的是什么?它不是像@user这样的对象吗? –

1
describe "return value of authenticate method", focus: true do 

    before do 
     @user = FactoryGirl.create(:user) 
    end 

    let(:found_user) { User.find_by_email(@user.email) } 

    it "can return value of authenticate method" do 
     expect(:user).to eq found_user.authenticate(:password) 
    end 

    end 

有人可以提出一个更好的RSpec方法来做到这一点,但它会让你的测试工作。

+0

当我尝试,我得到'故障/错误:期待(:用户)。为了EQ found_user.authenticate(:密码) 预期:假 有:user' –

+0

此行错误“expect(:user).to eq found_user.authenticate(:password)'。您需要将有意义的值传递给'expect'和'authenticate',而不仅仅是符号。 – dwhalen