2016-09-19 38 views
3

这是我的第一个rspec测试 我使用的是Hurtl的教程,并认为它已过时。 我想改变这条线,因为its不再rspec的一部分:RuntimeError:#let或#subject不带块调用

its(:user) { should == user } 

我试着这样做:

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

但得到一个错误

RuntimeError: #let or #subject called without a block

这是我的全面rspec测试,如果你需要它:

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 

回答

1

您不能将its(:user) { should == user }直接翻译为expect(subject.user).to eq(user)。你有一个it

it 'has a matchting user' do 
    expect(subject.user).to eq(user) 
end 
1

是包围它,因为M.哈特尔的Railstutorial书现在使用MINITEST而不是RSpec的你一定是以下过时的版本。

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

因为你没有在it块包装它调用subject不工作。

你可以把它改写为:

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

或者你可以使用rspec-its宝石,它可以让您使用its语法使用RSpec的最新版本。

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

,但它仍然不是一个特别有价值的测试,因为你只是测试测试本身,而不是应用程序的行为。

此外,此规格适用于在模型级别上进行质量分配保护的钢轨较旧版本(前3.5)。

您可以在https://www.railstutorial.org/找到当前版本的Rails Turorial书籍。