2016-09-19 57 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書籍。