I'm trying to DRY my code by putting a hash into a let and just calling the let but it doesn't seem to work. I get these errors:
syntax error, unexpected =>, expecting '}' (SyntaxError) "email" => user.email,
syntax error, unexpected =>, expecting :: or '[' or '.' ...l" => user.email, "password" => user.password }
Here's my test:
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
And here's my code:
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
You're missing one pair of braces.
let(:user_params) { "email" => user.email, "password" => user.password }
should be
let(:user_params) { {"email" => user.email, "password" => user.password} }
I would prefer a bit longer explanation. When you write something like this:
let(:user_params) { "email" => user.email, "password" => user.password }
You call method let
with one parameter (:user_params
) and a block (in this case { "email" => user.email, "password" => user.password }
). I will state it again:
let(:something) { some_method_call }
and
let(:something) do
some_method_call
end
are equal. By using let, RSpec sets variable to the result of the block. So, inside of the block, you need to return something. In this case - hash:
let(:user_params) do
{ "email" => user.email, "password" => user.password }
end
That's it! You can find out more about let on APIdock
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With