我写这个来测试我的控制器使用嵌套资源的创建操作。我有一个带有has_many :users
关联的 Account 模型。注册后,将创建一个具有单个用户的帐户。
describe "POST #create", focus: true do
let(:account) { mock_model(Account).as_null_object }
before do
Account.stub(:new).and_return(account)
end
it "creates a new account object" do
account_attributes = FactoryGirl.attributes_for(:account)
user_attributes = FactoryGirl.attributes_for(:user)
account_attributes[:users] = user_attributes
Account.should_receive(:new).with(account_attributes).and_return(account)
post :create, account: account_attributes
end
end
这是我得到的失败输出;注意预期和得到之间的区别:它在得到一个字符串时期望一个符号。
1) AccountsController POST #create creates a new account object
Failure/Error: Account.should_receive(:new).with(account_attributes).and_return(account)
<Account(id: integer, title: string, subdomain: string, created_at: datetime, updated_at: datetime) (class)> received :new with unexpected arguments
# notice that expected has symbols while the other users strings...
expected: ({:title=>"ACME Corp", :subdomain=>"acme1", :users=>{ ... }})
got: ({"title"=>"ACME Corp", "subdomain"=>"acme1", "users"=>{ ... }})
# ./spec/controllers/accounts_controller_spec.rb:34:in `block (3 levels) in <top (required)>'
我不禁注意到这段代码也有点味道。我不知道我是否正确。我是 RSpec 的新手,所以如果你能对我的努力提供一些反馈,我会加分。