这是我的第一次测试
我正在使用Hurtl的教程,并认为它已经过时了。
我想更改此行,因为 its(:user) { should == user }
不再是rspec的一部分:
expect(subject.user).to eq(user)
我试着这样做:
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
但是收到错误
RuntimeError:#let或#subject在没有块的情况下调用
如果您需要,这是我的完整rspec测试:
id
答案 0 :(得分:3)
您无法将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 :(得分:1)
是的,你必须遵循一个过时的版本,因为M. Hartl的Railstutorial书现在使用的是Minitest而不是RSpec。
expect(subject.user).to eq(user)
不起作用,因为您在subject
调用it
而不将其包含在it "should be associated with the right user" do
expect(subject.user).to eq(user)
end
块中。
您可以将其重写为:
rspec-its
或者您可以使用its
gem,它允许您将# with rspec-its
its(:user) { is_expected.to eq user }
# or
its(:user) { should eq user }
语法与当前版本的RSpec一起使用。
extract_first()
但它仍然不是一个特别有价值的测试,因为您只是测试测试本身而不是应用程序的行为。
此规范也适用于较旧版本(3.5之前版本)的轨道,其中在模型级别上进行了质量分配保护。
您可以在https://www.railstutorial.org/找到当前版本的Rails Turorial书。