Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RuntimeError: #let or #subject called without a block

This is my first rspec test I was using Hurtl's tutorial and figured that it is outdated. I want to change this line because its is no longer a part of rspec:

  its(:user) { should == user }

I tried to do this:

  expect(subject.user).to eq(user)

But get an error

RuntimeError: #let or #subject called without a block

This is my full rspec test if you need it:

require 'spec_helper'
require "rails_helper" 

describe Question do

  let(:user) { FactoryGirl.create(:user) }
  before { @question = user.questions.build(content: "Lorem ipsum") }

  subject { @question }

  it { should respond_to(:body) }
  it { should respond_to(:title) }
  it { should respond_to(:user_id) }
  it { should respond_to(:user) }

  expect(subject.user).to eq(user)
  its(:user) { should == user }

  it { should be_valid }

  describe "accessible attributes" do
    it "should not allow access to user_id" do
      expect do
        Question.new(user_id: user.id)
      end.to raise_error(ActiveModel::MassAssignmentSecurity::Error)
    end
  end

  describe "when user_id is not present" do
    before { @question.user_id = nil }
    it { should_not be_valid }
  end
end
like image 960
user2950593 Avatar asked Sep 19 '16 13:09

user2950593


1 Answers

Yes, you must be following an outdated version since M. Hartl's Railstutorial book now uses Minitest instead of RSpec.

expect(subject.user).to eq(user)

Does not work since you are calling subject without wrapping it in a it block.

You could rewrite it as:

it "should be associated with the right user" do
  expect(subject.user).to eq(user)
end

Or you can use the rspec-its gem which lets you use the its syntax with the current version of RSpec.

# with rspec-its
its(:user) { is_expected.to eq user }
# or
its(:user) { should eq user }

But its still not a particularly valuable test since you are just testing the test itself and not the behaviour of the application.

Also this spec is for an older version (pre 3.5) of rails where mass assignment protection was done on the model level.

You can find the current version of the Rails Turorial book at https://www.railstutorial.org/.

like image 200
max Avatar answered Oct 20 '22 05:10

max