RSpec测试实例变量到ID,带有eq解释

时间:2015-08-13 21:25:03

标签: rspec

在以下规范中

describe 'PUT update' do
  before :each do
    @contact = Factory(:contact, firstname: "Lawrence", lastname: "Smith")
  end

  context "valid attributes" do
    it "located the requested @contact" do
      put :update, id: @contact, contact: Factory.attributes_for(:contact)
      assigns(:contact).should eq(@contact)      
    end
  end
end

什么是assigns(:contact).should eq(@contact)测试?是否测试@contact是否等于@contact的id ...?那么为什么id: @contact而不是整个@contact

1 个答案:

答案 0 :(得分:1)

Rails在这里为你做了一些魔术。当你拨打这一行时

put :update, id: @contact, contact: Factory.attributes_for(:contact)

rails会自动查找id @contact并将其作为id参数的值

传递

assigns(:contact).should eq(@contact)正在检查更新此内容的控制器方法"联系"正在设置一个名为@contact的实例变量,其数据与您的测试联系人相同

您可能会更清楚地更改了一些变量名称(我在您的测试中将@contact重命名为@test_contact

describe 'PUT update' do
  before :each do
    @test_contact = Factory(:contact, firstname: "Lawrence", lastname: "Smith")
  end

  context "valid attributes" do
    it "located the requested @contact" do
      put :update, id: @test_contact, contact: Factory.attributes_for(:contact)
      assigns(:contact).should eq(@test_contact)      
    end
  end
end