2014-01-24 59 views
2

我試圖通過將一個散列放入一個let中並乾脆調用let來幹掉我的代碼,但它似乎不起作用。我得到這些錯誤:在let中使用散列()

syntax error, unexpected =>, expecting '}' (SyntaxError) "email" => user.email, 

syntax error, unexpected =>, expecting :: or '[' or '.' ...l" => user.email, "password" => user.password } 

這裏是我的測試:

describe '#create' do 
    let(:user) { create(:user) } 
    let(:user_params) { "email" => user.email, "password" => user.password } 
    before(:each) { User.stub(:find_by_email).and_return(user) } 
    it "should send find message to user model" do 
    User.should_receive(:find_by_email) 
    post :create, locale: "es", user: { user_params } 
    end 
    it "should set user to @user" do 
    post :create, locale: "es", user: { "email" => user.email, "password" => user.password } 
    assigns(:user).should eq(user) 
    end 
end 

這裏是我的代碼:

def create 
    @user = User.find_by_email(params[:email]) 
    if @user && @user.authenticate(params[:password]) 
    session[:user_id] = @user.id 
    redirect_to root_url 
    else 
    render 'login' 
    end 
end 

回答

9

你錯過了一對大括號。

let(:user_params) { "email" => user.email, "password" => user.password } 

應該

let(:user_params) { {"email" => user.email, "password" => user.password} } 
+0

這就是完全它。謝謝! – freddyrangel

6

我寧願長一點的解釋。 當你寫這樣的事:

let(:user_params) { "email" => user.email, "password" => user.password } 

你調用方法let有一個參數(:user_params)和塊(在這種情況下{ "email" => user.email, "password" => user.password })。我要再次聲明它:

let(:something) { some_method_call } 

let(:something) do 
    some_method_call 
end 

是相等的。通過使用let,RSpec將變量設置爲該塊的結果。因此,在塊內部,你需要返回一些東西。在這種情況下 - 散列:

let(:user_params) do 
    { "email" => user.email, "password" => user.password } 
end 

就是這樣!你可以找到更多關於讓

+0

我不知道。這很好。謝謝! – freddyrangel