在let()中使用哈希

时间:2014-01-24 15:31:54

标签: ruby-on-rails ruby rspec

我试图通过将一个哈希放入一个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

2 个答案:

答案 0 :(得分:13)

你缺少一对牙箍。

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

应该是

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

答案 1 :(得分:8)

我更喜欢更长的解释。 当你写这样的东西时:

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

就是这样!您可以在APIdock

了解更多信息